package com.resource.allocator.controller;

import java.io.IOException;

import javax.persistence.EntityManager;
import javax.persistence.Query;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.resource.allocator.EMF;
import com.resource.allocator.model.Resource;
import com.resource.allocator.model.Skill;

@SuppressWarnings("serial")
public class ResourcesController extends HttpServlet {
    private EntityManager em;

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp)
	    throws ServletException, IOException {
	String action = (String) req.getParameter("action");
	String targetPage = "";

	if ("".equals(action) || action == null) {
	    actionListing(req);
	    targetPage = "/resourceList.jsp";
	} else if ("create".equals(action)) {
	    // return a resource or null if it's new resource.
	    req.setAttribute("aResource", handleForm(req));
	    targetPage = "/resourceEdit.jsp";
	} else if ("edit".equals(action)) {
	    // return a resource or null if it's new resource.
	    req.setAttribute("aResource", prepareEdit(req));
	    targetPage = "/resourceEdit.jsp";
	} else if ("addskill".equals(action)) {
	    targetPage = "/skillEdit.jsp";
	}
	getServletContext().getRequestDispatcher(targetPage).forward(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp)
	    throws ServletException, IOException {
	String action = (String) req.getParameter("action");
	String targetPage = "";
	System.out.println("ResourcesController::doPost::" + action);

	if (action != null) {
	    if ("create".equals(action) || "edit".equals(action)) {
		try {
		    em = EMF.get().createEntityManager();
		    em.persist(handleForm(req));
		    System.out.println("save!!");
		} catch (Exception e) {
		    e.printStackTrace();
		} finally {
		    em.close();
		}
		targetPage = "/resourceList.jsp";
	    } else if ("addskill".equals(action)) {
		String skillStr = req.getParameter("skillName");
		String resourceKey = req.getParameter("resourceKey");
		Skill sk = new Skill();		
		if (skillStr != null && skillStr.length() > 0) {
		    sk.setName(skillStr);
		    try {
			em = EMF.get().createEntityManager();
			em.persist(sk);
			System.out.println("save!!");
		    } catch (Exception e) {
			e.printStackTrace();
		    } finally {
			em.close();
		    }
		}
		targetPage = "/resourceEdit.jsp";
	    }
	}
	actionListing(req);
	resp.sendRedirect(targetPage);
    }

    @SuppressWarnings("unchecked")
    private void actionListing(HttpServletRequest req) {
	// em = EMF.get().createEntityManager();
	// List<Resource> resources = null;
	// try {
	// em.setFlushMode(FlushModeType.COMMIT);
	// Query q =
	// em.createQuery("select r from Resource r order by r.capacity desc");
	// resources = q.getResultList();
	// req.setAttribute("resourceList", resources);
	// } finally {
	// em.close();
	// }
    }

    private Resource prepareEdit(HttpServletRequest req) {
	String key = req.getParameter("key");
	Resource r = new Resource();
	if (key != null && !"".equals(key)) {
	    em = EMF.get().createEntityManager();
	    try {
		Query q = em.createQuery("select r from Resource r where r.key = :key");
		q.setParameter("key", key);
		r = (Resource) q.getSingleResult();
	    } finally {
		em.close();
	    }
	}
	return r;
    }

    private Resource handleForm(HttpServletRequest req) {
	// String key = req.getParameter("key");
	String firstName = req.getParameter("firstName") == null ? ""
		: req.getParameter("firstName");
	String lastName = req.getParameter("lastName") == null ? ""
		: req.getParameter("lastName");
	String capacity = req.getParameter("capacity");
	String skill = req.getParameterValues("skills") == null ? ""
		: req.getParameterValues("skills").toString();

	System.out.println("firstname: " + firstName);
	System.out.println("TODO :createOrUpdate:skill: " + skill);
	Resource r = new Resource();
	r.setFirstName(firstName);
	r.setLastName(lastName);
	r.setCapacity((capacity != null ? Integer.parseInt(capacity) : 0));
	// TODO parse skills
	r.setSkills(skill.toString());
	return r;
    }
}
